import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../database/prisma.service';

/**
 * 审计服务
 */
@Injectable()
export class AuditService {
  private readonly logger = new Logger(AuditService.name);

  constructor(private readonly prisma: PrismaService) {}

  async logAuditEvent(data: {
    user_id?: number;
    user_type: string;
    action: string;
    resource_type: string;
    resource_id?: string;
    ip_address?: string;
    user_agent?: string;
    request_data?: any;
    response_data?: any;
    error_message?: string;
    execution_time_ms?: number;
    severity: string;
    correlation_id?: string;
  }): Promise<void> {
    try {
      await this.prisma.auditLog.create({
        data: {
          ...data,
          created_at: new Date(),
        },
      });
    } catch (error) {
      this.logger.warn('记录审计日志失败', {
        error: error.message,
        action: data.action,
        resource_id: data.resource_id,
      });
    }
  }
}